
<template>
  <div
    class="goTopRoot flex3"
    :class="[isGoTopShow ?  'showBtn' : isFirst ? '':'hideBtn' ]"
    @click="goTop"
  >
    <i class="iconfont icon-fanhuidingbu"></i>
  </div>
</template>

<script>
let obj = null;
export default {
  props: {
    scrollObj: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      isGoTopShow: false,
      isFirst: true
    };
  },
  mounted() {
    this.$nextTick(() => {
      if (obj == null && this.scrollObj === "") {
        obj = document;
        this.el = document.body;
      } else if (this.scrollObj) {
        obj = document.querySelector(this.scrollObj);
        this.el = obj;
      }
      obj.addEventListener("scroll", this.scroll);
    });
  },
  destroyed() {
    obj.removeEventListener("scroll", this.scroll);
  },
  methods: {
    goTop() {
      console.log("goTop");
      console.log(obj);
      obj.scrollTo({
        behavior: "smooth",
        top: 0
      });
    },
    scroll() {
      if (this.el.scrollTop >= 500 && !this.isGoTopShow) {
        this.isGoTopShow = true;
        if (this.isFirst) {
          this.isFirst = false;
        }
      } else if (this.el.scrollTop < 500 && this.isGoTopShow) {
        this.isGoTopShow = false;
      }
    }
  }
};
</script>

<style scoped  >
.goTopRoot {
  position: fixed;
  bottom: -55px;
  right: 40px;
  height: 40px;
  width: 40px;
  border-radius: 50%;
  background-color: #f8f8f8;
  border: 1px solid #eee;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  z-index: 10000;
}
.showBtn {
  animation: showBtn 0.7s ease;
  animation-fill-mode: forwards;
}
.hideBtn {
  animation: hideBtn 0.7s ease;
  animation-fill-mode: forwards;
}
@keyframes showBtn {
  0% {
    bottom: -55px;
  }
  50% {
    bottom: 110px;
  }
  100% {
    bottom: 85px;
  }
}
@keyframes hideBtn {
  0% {
    bottom: 85px;
  }
  100% {
    bottom: -55px;
  }
}
</style>
